<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-containers">
      <div class="filter-left">
        <el-input
          size="mini"
          v-model="listQuery.searchKey"
          placeholder="请输入名称搜索"
          style="width: 250px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          @input="handleFilter"
        />
      </div>
      <div class="filter-right">
        <el-button
          icon="el-icon-plus"
          type="primary"
          size="mini"
          @click="handleAddInfo"
        >
          新增
        </el-button>
      </div>
    </div>
    <div style="margin-bottom: 12px; margin-top: 12px">
      <el-link type="primary" :href="pdfhref" target="_blank"
        >点击查看使用说明文档<i class="el-icon-view el-icon--right"></i
      ></el-link>
    </div>
    <!-- table数据 -->
    <el-table
      :data="pageList"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="app_name" label="名称" align="center">
      </el-table-column>
      <el-table-column prop="app_code" label="编码" align="center">
      </el-table-column>
      <el-table-column
        prop="callback_url"
        label="授权完成跳转路径"
        align="center"
      >
      </el-table-column>
      <el-table-column label="创建时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.created_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.updated_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleToSysRolePage(scope.row)"
            >角色管理</el-button
          >
          
          <el-button type="text" size="small" @click="handleEdit(scope.row)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            :disabled="!isAdmin"
            @click="handleDelete(scope.row)"
            style="color: red"
            >删除</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleCopy(scope.row)"
            style="color: green"
            >复制授权链接</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getApiList"
    />

    <!-- 新增修改信息 -->
    <el-drawer
      size="50%"
      :close-on-press-escape="false"
      :visible.sync="dialogFormVisible"
      :wrapperClosable="false"
      :title="title"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" label-width="135px" prop="appName">
              <el-input
                v-model="form.appName"
                autocomplete="off"
                maxlength="100"
                placeholder="请输入名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="授权完成跳转路径"
              label-width="135px"
              prop="callbackUrl"
            >
              <el-input
                v-model="form.callbackUrl"
                autocomplete="off"
                maxlength="100"
                placeholder="请输入跳转路径"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="el_drawer_footerbtn">
        <el-button style="margin: 0 10px" @click="handleCancel"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleSubmit('form')"
          >确 定</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>
  <script>
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
// 导入模块
import vueJsonEditor from "vue-json-editor";
import { curentTime } from "@/filters/index";
import { getDataByCode } from "@/api/user";
import { getApiList, insertAuth, updateAuth, deleteAuth } from "@/api/accredit";
import { mapGetters } from "vuex"
export default {
  name: "Accredit",
  components: { Pagination, vueJsonEditor },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  computed: {
    ...mapGetters([
      'roles'
    ]),
  },
  data() {
    return {
      // 搜索值
      searchKey: "",
      // 表单控制
      dialogFormVisible: false,
      // 表单标题
      title: "",
      //   表单
      form: {
        id: "",
        appName: "",
        callbackUrl: "",
      },
      // 表单检验
      rules: {
        appName: [{ required: true, message: "请填写名称", trigger: "blur" }],
        callbackUrl: [
          { required: true, message: "请填写完成跳转路径", trigger: "blur" },
        ],
      },
      // 请求方式
      methodTypeLists: ["GET", "POST"],
      webapiDataObj: null,
      // table数据
      pageList: [],
      // 查询参数
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        searchKey: null,
      },
      //  总数量
      total: 0,
      pdfhref: "https://morefun.yuque.com/kd0dsy/pyy99r/itdib5exsplmme1g",
      isAdmin: false,
    };
  },
  async created() {
    this.isAdmin = this.roles.includes('admin');
    // 获取配置数据
    getDataByCode({ code: "RobotAlarm,OnJobUser,HttpData" }).then((res) => {
      this.webapiDataObj = res.data.HttpData || null;
    });

    this.getApiList();
  },
  methods: {
    //  跳转角色管理页面
    handleToSysRolePage(row) {
      this.$router.push({ path: "/accredit/sysrole",query: { appcode: row.app_code} });
    },
    // 获取api列表
    getApiList() {
      getApiList(this.listQuery).then((res) => {
        this.pageList = res.data.lists;
        this.total = res.data.total;
      });
    },

    // 按需查询
    async handleFilter() {
      this.listQuery.pageNum = 1;
      this.getApiList();
    },

    // 新增授权方法
    handleAddInfo() {
      this.title = "新增授权信息";
      delete this.form.id;
      this.form.appName = "";
      this.form.callbackUrl = "";
      this.$nextTick(() => {
        this.$refs["form"].resetFields();
      });
      this.dialogFormVisible = true;
    },

    // json编辑器回调方法
    onJsonSave(value) {
      this.hasJsonFlag = true;
    },
    // json编辑器回调方法
    onWebapiJsonSave(value) {
      this.hasJsonFlag = true;
    },
    onError(value) {
      this.hasJsonFlag = false;
    },

    // 提交表单信息
    handleSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.form.id) {
            updateAuth(this.form).then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.getApiList();
              this.dialogFormVisible = false;
            });
          } else {
            delete this.form.id;
            insertAuth(this.form).then((res) => {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.getApiList();
              this.dialogFormVisible = false;
            });
          }
        }
      });
    },

    // 取消
    handleCancel() {
      this.dialogFormVisible = false;
    },

    // 修改方法
    handleEdit(row) {
      console.log(row);
      this.title = "修改授权信息";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        if (this.$refs["form"]) {
          this.$refs["form"].clearValidate();
        }
        this.form.id = row.id;
        this.form.appName = row.app_name;
        this.form.callbackUrl = row.callback_url;
      });
    },

    // 删除方法
    handleDelete(row) {
      if(!this.isAdmin) return this.$message({ type: 'error', message: '请联系管理员执行该操作' });
      this.$confirm("此操作将删除该API授权信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteAuth({ id: row.id }).then((res) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getApiList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    handleCopy(row) {
      let name = row.auth_uri; //每一行的某个值
      var copyContent = document.createElement("input"); //创建一个隐藏input（重要！）
      copyContent.value = name; //拼接多个赋值
      document.body.appendChild(copyContent);
      copyContent.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
      this.$message.success("复制成功！");
      copyContent.remove();
    },
  },
};
</script>
    
    <style lang="scss">
.filter-containers {
  display: flex;
  justify-content: space-between;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
      